<template>
    <div v-if="visible" class="node-editor">
      <h3>编辑节点信息</h3>
      <textarea v-model="jsonString" rows="10" cols="50"></textarea>
      <button @click="applyChanges">应用更改</button>
      <button @click="deleteNodes">删除</button>
      <button @click="addSiblingNode">增加同级节点</button>
      <button @click="addChildNode">增加下级节点</button>
      <button @click="close">关闭</button>
    </div>
    <NodeCreationDialog
      v-if="showCreationDialog.value"
      :visible="showCreationDialog.value"
      :parentNode="nodeData.value"
      :data="props.data"
      @close="showCreationDialog.value = false"
      @create="handleNodeCreation"
    />
  </template>
  
  <script setup>
  import { ref, watch } from 'vue';
  import { updateNode, deleteNode, addNode } from '../../utils/treeNodeUtils';
  import { ElMessage } from 'element-plus';
  import NodeCreationDialog from './NodeCreationDialog.vue'; // 引入新组件
  // 父组件可以通过 props 向子组件传递数据
  const props = defineProps({
    node: Object,
    visible: Boolean,
    data: Array
  });
  
  const emit = defineEmits(['close']); // 定义 close 事件
  
  const nodeData = ref({ ...props.node });
  const jsonString = ref(JSON.stringify(nodeData.value, null, 2)); // 初始化 JSON 字符串
  
  watch(() => props.node, (newNode) => {
    nodeData.value = { ...newNode };
    jsonString.value = JSON.stringify(nodeData.value, null, 2); // 更新 JSON 字符串
  });
  
  const applyChanges = () => {
    try {      
      const updatedData = JSON.parse(jsonString.value); // 解析 JSON 字符串
      updateNode(props.data, nodeData.value.id, updatedData); // 更新节点数据
      nodeData.value = updatedData; // 更新本地数据
    } catch (error) {
      alert('JSON 格式错误，请检查输入。'); // 错误处理
    }
  };
  
  const deleteNodes = () => {
    deleteNode(props.data, nodeData.value);
    // 点击删除节点后，应当关闭编辑器
    emit('close'); // 触发 close 事件
    // 弹出悬浮提示框显示删除成功
    ElMessage({
      message: '删除成功',
      type: 'success',
    });
  };
  
  const showCreationDialog = ref(false);
  
  const addSiblingNode = () => {
    showCreationDialog.value = true;
    console.log('addSiblingNode called, showCreationDialog:', showCreationDialog.value); // 调试信息
  };
  
  const addChildNode = () => {
    showCreationDialog.value = true;
    console.log('addChildNode called, showCreationDialog:', showCreationDialog.value); // 调试信息
  };
  
  const handleNodeCreation = (newNode) => {
    if (newNode.type === 'leaf') {
      addNode(props.data, props.node.parent, newNode);
    } else {
      addNode(props.data, nodeData.value, newNode);
    }
  };
  
  const close = () => {
    emit('close'); // 触发 close 事件
  };
  </script>
  
  <style scoped>
  .node-editor {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    z-index: 1001;
  }
  
  textarea {
    width: 100%;
    margin-bottom: 10px;
  }
  </style>